﻿// JavaScript Document
var speedForStill = [4,10],mousePos = {x:0,y:0},geocoder = null;// new google.maps.Geocoder();;//google 解析地址的对象 geocoder = new GClientGeocoder();
window.isIE = window.ActiveXObject?true:false;
(function(){   
	var ua = navigator.userAgent.toLowerCase(),   
	 	check = function(r){return r.test(ua);};
	window.isIE7 = isIE && check(/msie 7/),   
	window.isIE8 = isIE && check(/msie 8/),
	window.isIE6 = isIE && !isIE7 && !isIE8;
})();
//调用googleAPI进行地址解析
function parseAddress (weidu,jingdu,arr){
	if(typeof google == 'undefined'){
		return;
	}
	if(geocoder==null){
		geocoder = new google.maps.Geocoder();
	}
	arr = typeof arr ==='string'?document.getElementById(arr):arr;
	if(arr.nodeType){
		geocoder.geocode({"address":weidu+","+jingdu}, function(results,status) {
			_str = " ";
			if (status == google.maps.GeocoderStatus.OK) {
				_str = results[0].formatted_address;
			}else{
				_str = lg.isGetting;
			}
			arr.innerHTML=_str;
			arr.setAttribute('title', results[0].formatted_address);
		});
	}
}
//通过偏移角度和速度计算方向
function getHangXiang(dusu, sudu){
	if(sudu < 0||dusu=="") return "......";
	var z = 5,fz = 10,p = 30;
	var hangxiang = GTS.lang.hangxiang;
	var qujian1 = [ z, fz, fz, p, 90 - p, 90 - z, 90 - fz, 90 + fz, 90 + p,180 - p, 180 - z, 180 - fz, 180 + fz, 180 + p, 270 - p, 270 - z,270 - fz, 270 + fz, 270 + p, 360 - p ];
	var qujian2 = [ 360 - z, 360 - fz, p, 90 - p, 90 - fz, 90 + z, 90 + fz,90 + p, 180 - p, 180 - fz, 180 + z, 180 + fz, 180 + p, 270 - p,270 - fz, 270 + z, 270 + fz, 270 + p, 360 - p, 360 - fz ];
	for ( var i = 0; i < qujian1.length; i++) {
		if (i == 0 || i == 1) {
			if (qujian2[i] <= dusu || dusu <= qujian1[i])
				return hangxiang[i];
		} else {
			if (qujian1[i] <= dusu && dusu <= qujian2[i])
				return hangxiang[i];
		}
	}
	return dusu;
}
//把秒转化为基本的日期格式
function exchangeTime(msecond) {
	var dd,hh,mm,ss;//天、时、分、秒
	dd = Math.round(msecond / 86400 + 0.5) - 1;
	hh = Math.round((msecond - dd * 86400) / 3600 + 0.5) - 1;
	mm = Math.round((msecond - dd * 86400 - hh * 3600) / 60 + 0.5) - 1;
	ss = Math.round(msecond - dd * 86400 - hh * 3600 - mm * 60);
	var strtip = "";
	if (dd > 0)
	    strtip = strtip + dd + GTS.lang.s_Title_Date;
	if (hh > 0)
	    strtip = strtip + hh + GTS.lang.s_Title_toHours;
	if (mm > 0){
	    strtip = strtip + mm + GTS.lang.s_Title_toMunite;
		if(dd > 0)
			return strtip;
	}
	if (ss > 0)
	    strtip = strtip + ss + GTS.lang.s_TitleSecond;
	return strtip;
}
//获取俩个时间的时间差
function getTimeDiff(serverTime, objTime){
	var timeDiff = 0, type = typeof serverTime;
	if(type == 'number')
		timeDiff = serverTime - objTime;
	else if(type == 'string')
		timeDiff = new Date((serverTime.split("."))[0].replace(/-/g, "/")) - new Date((objTime.split("."))[0].replace(/-/g, "/"));
	return timeDiff < 0?1:(timeDiff/1000);
}
//根据经纬度的距离获取地图的缩放级
function getRoom(diff){
	var room = new Array(0,  1,  2, 3, 4, 5, 6,7,8,  9,   10,  11,  12,  13, 14);
	var diffArr = new Array(360,180,90,45,22,11,5,2.5,1.25,0.6,0.3,0.15,0.07,0.03,0);
	for(var i = 0; i < diffArr.length; i ++){
		if((diff - diffArr[i]) >= 0){
			return room[i];
		}
	}	
	return 14;
}
//更新鼠标位置
function mouseCoords(ev){ 
	ev= ev || window.event; 
	if(ev.pageX || ev.pageY){ 
		mousePos = {x:ev.pageX+10, y:ev.pageY+10}; 
	} 
	mousePos = { 
		x:ev.clientX + document.documentElement.scrollLeft - document.body.clientLeft+10,
		y:ev.clientY + document.documentElement.scrollTop   - document.body.clientTop+10
	}; 
}
function getStatic(datetime,servertime,sys_time,heart_time){//判断是否静止
	var stopover_time = getTimeDiff1(servertime, sys_time);
	var heart_time = getTimeDiff1(servertime, heart_time);
	var dingwei_time = getTimeDiff1(servertime, sys_time);	
    if(dingwei_time < heart_time)heart_time = dingwei_time;	
	return [heart_time,stopover_time];
}
function getCenterPoint(maxJ,minJ,maxW,minW){//通过经纬度获取中心位置和缩放级别
	if(maxJ==minJ&&maxW==minW)return [maxJ,maxW,0];
	var diff = maxJ - minJ;
	if(diff < (maxW - minW))diff = maxW - minW;
	diff = parseInt(10000 * diff)/10000;	
	var centerJ = minJ*1000000+1000000*(maxJ - minJ)/2;
	var centerW = minW*1000000+1000000*(maxW - minW)/2;
	return [centerJ/1000000,centerW/1000000,diff];
}
/*
 * @description 计算设备运行状态
 * @return {Array} marker的颜色、设备状态、速度、是否在线、是否显示缴费信息
 * @param heart_time {Number} 服务器时间与设备心跳时间差值
 * @param speed {Number} 设备速度，-9表示未上线
 * @param stopover_time {Number} 服务器时间与最近移动定位时间差值
 * @param endServerTimeCount {Number} 设备过期时间（服务器时间和到期时间的差返回的秒数），大于0表示已过期，等于0表示今日到期
 * @param isShip {Boolean} 是否是船舶
 */
 //获取状态和速度
function status_(heart_stime,speed,stopover_time,endServerTimeCount,islac){//状态和状态标识 endServerTimeCount表示服务器时间和到期时间的差返回的秒数

    var isOnlineOrOffline = false; //判断是否在线或离线
    var speed = parseInt(speed);
    var showPayTip = false;//是否显示缴费信息
    isOnlineOrOffline = checkOff(heart_stime);
    
     var _arr = ["white", GTS.lang.s_Title_CarOffline, speed, isOnlineOrOffline,showPayTip];
    
	
    if (speed < 0) _arr = ["gray", GTS.lang.s_Title_CarOffline, 0, isOnlineOrOffline,showPayTip];
    else if (speed >= 0 && speed < speedForStill[1])
        _arr = ["gray", GTS.lang.s_Title_CarStop, 0, isOnlineOrOffline,showPayTip];
    else if (speed < 80 && speed >= speedForStill[1])
        _arr = ["green", GTS.lang.s_Title_CarSpeed, speed, isOnlineOrOffline,showPayTip];
    else if (speed >= 80 && speed < 120)
        _arr = ["yellow", GTS.lang.s_Title_CarFestSpeed, speed, isOnlineOrOffline,showPayTip];
    else if (speed < 80 && speed >= speedForStill[1])
        _arr = ["red", GTS.lang.s_Title_CarOverSpeed, speed, isOnlineOrOffline,showPayTip];
    if(islac==1)_arr = ["green",GTS.lang.s_Title_CarLac,speed,isOnlineOrOffline,showPayTip];
	return _arr;
}
 /*
function status_(heart_stime,speed,stopover_time,endServerTimeCount,isShip){
	speed = Number(speed);
	var oneDay = 60*60*24;
	var servenDays = -(60*60*24*7);
	var offlineSeconds = 600;//设备离线的时长参照值
	var showPayTip = false;//是否显示缴费信息
	if(endServerTimeCount>(oneDay*7) && speed != -9){//已经过期7天以上 不显示速度，并且地图上也不显示
		showPayTip = true;
		return ["white",lg.arrear,0,false,showPayTip];
	}
	var statusWord = lstatusWord = "-1";
	if(endServerTimeCount<=(oneDay*7)&&endServerTimeCount>0){//已经过期0-7天的设备 不显示速度，但地图上可以显示
		var days = parseInt(endServerTimeCount/oneDay)+lg.d;
		statusWord = lg.serviceEnd[0]+days;
		showPayTip = true;
	}
	if(endServerTimeCount<=0&&endServerTimeCount>servenDays){//表示7天内将过期
		var days = parseInt(Math.abs(endServerTimeCount)/oneDay);
		statusWord = days+lg.serviceEnd[2];
		if(endServerTimeCount==0){
			statusWord = lg.serviceEnd[3];
		}
		showPayTip = true;
	}
	if(speed==-9&&heart_stime > offlineSeconds){
		return ["white",statusWord == "-1"?lg.srun0:statusWord,0,false,showPayTip];
	}
	if(speed==-9&&heart_stime <=offlineSeconds){
		return ["gray",statusWord == "-1"?lg.srun2:statusWord,0,true,showPayTip];
	}
	if(speed<0||heart_stime > offlineSeconds){
		return ["white",statusWord == "-1"?lg.srun1:statusWord,0,false,showPayTip];
	}
	if(35 < stopover_time){
		return ["gray",statusWord == "-1"?lg.srun2:statusWord,0,true,showPayTip];
	}
	//船舶只要有速度就判断为行驶
	if(isShip){
		if(speed==0){//如果服务器时间减去最新移动定位时间，大于2个信号周期，判读为静止
			return ["gray",statusWord == "-1"?lg.srun2:statusWord,0,true,showPayTip];
		}else if(speed>0 && speed<=80)
			return ["green",statusWord == "-1"?lg.srun3:statusWord,speed,true,showPayTip];
	}else{
		if((speed>=0&&speed<speedForStill[1])){//如果服务器时间减去最新移动定位时间，大于2个信号周期，判读为静止
			return ["gray",statusWord == "-1"?lg.srun2:statusWord,0,true,showPayTip];
		}
		if(speed>=speedForStill[1]&&speed<=80){
			return ["green",statusWord == "-1"?lg.srun3:statusWord,speed,true,showPayTip];
		}
	}
	if(speed>80&&speed<=120){
		return ["yellow",statusWord == "-1"?lg.srun4:statusWord,speed,true,showPayTip];
	}
	if(speed>120){
		return ["red",statusWord == "-1"?lg.srun5:lstatusWord,speed,true,showPayTip];
	}
	return ["white",lg.srun1,0,false,showPayTip];
}*/


function direction(speed,iconType,hangxiang){//方向标识
	var direction = "west";
	if(String(iconType).charAt(0)=="2"){
		speed = Number(speed);
		hangxiang = Number(hangxiang);
		if(speed==-1){
			direction = "west";
		}else{
			if(hangxiang<=45||hangxiang>315){//北向
				direction = "north";
			}else if(hangxiang>45&&hangxiang<=135){//东向
				direction = "east";
			}else if(hangxiang>135&&hangxiang<=225){//南向
				direction = "south";
			}else if(hangxiang>225&&hangxiang<=315){//西向
				direction = "west";
			}
		}
	}
	return direction;
}

//通过图片类型 状态 方向 拼成marker图片
function getIconURL(iconType,status,hangxiang){
	if(typeof iconType != 'string'){
		iconType = parseInt(iconType);
		iconType = iconType<10?('0'+iconType):String(iconType);
	}
	var imgURL = "green_01.png";
	if(iconType.charAt(0)=="2"){
		imgURL = status+"_"+hangxiang+"_"+iconType+".png";
	}else{
		imgURL = status+"_"+iconType+".png";
	}
	return imgURL;
}
//解析ACC状态信息
function getAccStatus(val, p, record){//type,val
	if((typeof record)=="undefined"||record.data["product_type"]=="GT06"){
		var stem = parseInt(val.substr(0,2),16);
		var tem = stem.toString(2);
		if(tem.length<2||tem.substr(tem.length-2,1)=="0"){return lg.off;}
		else {return lg.on;}
	}else{
		return "...";	
	}
}
//加载JS
function loadFile(arr,scriptId,callback){//需要加载的JS数组
	var oHead = document.getElementsByTagName('HEAD').item(0);
	if(isArray(arr)){
		if((typeof scriptId) == "undefined"){
			scriptId = [];
		}
		if((typeof callback) == "undefined"){
			callback = [];
		}
		for(var i=0;i<arr.length;i++){
			var _n = loadOneFile(arr[i],scriptId[i],callback[i]);
			oHead.appendChild(_n); 
		}
	}else{
		var _n = loadOneFile(arr,scriptId,callback);
		oHead.appendChild(_n); 
	}
}
function loadOneFile(name,id,cb){
	//var oHead = document.getElementsByTagName('HEAD').item(0);
	var oScript= document.createElement("script");
	oScript.type = "text/javascript"; 
	var _C = "";
	if((typeof id) != "undefined"){
		oScript.id = id;
	}
	if((typeof cb) != "undefined"){
		if(name.indexOf("?")>-1){
			_C = "&callback="+cb+"&t=" + new Date().getTime();
		}else{
			_C = "?callback="+cb+"&t=" + new Date().getTime();
		}
	}
	oScript.src=name+_C; 
	return oScript;
	//oHead.appendChild(oScript); 
}
//删除一个JS文件
function deleteFile(id){
	var script;	
	while(script = document.getElementById(id)){
		_.dom.remove(script);
	}
}
//判断v的类型是否为数组
function isArray(v){
	var toString = Object.prototype.toString;
	return toString.apply(v) === '[object Array]';   
}   
function distance(lat1,lon1,lat2,lon2,len) {//获取地图上俩个点之间的距离
	var R = 6371; // km (change this constant to get miles)
	var dLat = (lat2-lat1) * Math.PI / 180;
	var dLon = (lon2-lon1) * Math.PI / 180; 
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
		Math.cos(lat1 * Math.PI / 180 ) * Math.cos(lat2 * Math.PI / 180 ) * 
		Math.sin(dLon/2) * Math.sin(dLon/2); 
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c;
	return d+len;
}
function formatKm2M(v){//把KM转化成需要是数据格式
    if (v > 1) return Math.round(v * 1000) / 1000 + GTS.lang.s_TitleKilometers;
    else if (v <= 1) return Math.round(v * 1000) + GTS.lang.s_TitleMeters;
}
//解析GT06的数据定位状态
function parseGt06Staust(val){
	val = val+"";
	if((typeof val) == "undefined")return lg.sdw0;
	var stem = parseInt(val.substr(0,2),16);
	var tem = stem.toString(2);
	if(tem.length<7||(tem.length ==7&&tem.substr(0,1)=="0")||(tem.length ==8&&tem.substr(1,1)=="0"))return lg.sdw0;
	else return lg.sdw1;
}
function getInterceptedStr(sSource, iLen) {
	sSource = String(sSource);
    if (sSource.replace(/[^\x00-\xff]/g, "xx").length <= iLen) {
        return sSource;
    }
    var str = "";
    var l = 0;
    var schar;
    for (var i = 0; schar = sSource.charAt(i); i++) {
        str += schar;
        l += (schar.match(/[^\x00-\xff]/) != null ? 2: 1);
        if (l >= iLen) {
            str += "....";
            break;
        }
    }
    return str;
}
//UTC + 时区差 ＝ 本地时间 
//将后台utc时间毫秒转为本地时间
function utcToLocal(utc){
	if(isNaN(Number(utc))) return utc;
	var t = new Date(Number(utc));
	d = [t.getFullYear(), t.getMonth()+1, t.getDate()].join('/');
	var mm = t.getMinutes() , ss = t.getSeconds();
	d += ' ' + ([t.getHours(), mm > 9 ? mm : '0'+mm, ss > 9 ? ss : '0'+ss].join(':'));
	return d;
}

//将本地时间时间转为utc时间毫秒
function localToUtc(local){
	if(!isNaN(Number(local))) return local;
	return new Date(local.replace(/\-/g,'/')).getTime();
}


/*
*新添加函数开始
*/
function checkOff(gpsDate) {
    if (getTimeDiff1(gpsDate) > 30) {
        return false;
    } else {
        return true;
    }
}
function getTimeDiff1(endDate) {
    try {
        endDate = toDate(endDate);
        var startDate = new Date();
        return (startDate.getTime() - endDate.getTime()) / 60000;
    } catch (e) { }
    return 0;
}
function toDate(dateStr) {
    var regex1 = /^\d{4}\/\d{1,2}\/\d{1,2}$|^\d{1,2}\/\d{1,2}\/\d{4}$|^\d{4}\/\d{1,2}\/\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}$|^\d{1,2}\/\d{1,2}\/\d{4} \d{1,2}:\d{1,2}:\d{1,2}$/;
    var regex2 = /^\d{4}-\d{1,2}-\d{1,2}$/;
    var regex3 = /^\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}$/;

    if (regex1.test(dateStr)) {
        return new Date(dateStr);
    } else if (regex2.test(dateStr)) {
        var arr = dateStr.split("-");
        return new Date(arr[0], arr[1] - 1, arr[2]);
    } else if (regex3.test(dateStr)) {
        var arr1 = dateStr.split(" ");
        var arr2 = arr1[0].split("-");
        var arr3 = arr1[1].split(":");
        return new Date(arr2[0], arr2[1] - 1, arr2[2], arr3[0], arr3[1], arr3[2])
    } else {
        return null;
    }
}
function getDateDiff(dateTimeStamp) {
    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - toDate(dateTimeStamp).getTime();
    if (diffValue < 0) {
        //非法操作          
        //alert("结束日期不能小于开始日期！");  
    }
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;
    if (monthC >= 1) {
        result = GTS.lang.s_Title_Overto + parseInt(monthC) + GTS.lang.s_Title_toMonth;
    } else if (weekC >= 1) {
        result = GTS.lang.s_Title_Overto + parseInt(weekC) + GTS.lang.s_Title_toDay;
    } else if (dayC >= 1) {
        result = parseInt(dayC) + GTS.lang.s_Title_Date + parseInt(hourC) % 24 + GTS.lang.s_Title_toHours;
    } else if (hourC >= 1) {
        result = parseInt(hourC) + GTS.lang.s_Title_toHours + parseInt(minC) % 60 + GTS.lang.s_Title_toMunite;
    } else if (minC >= 1) {
        result = parseInt(minC) + GTS.lang.s_Title_toMunite;
    } else
        result = GTS.lang.s_Title_CarUpdata;
    return result;
} 
/*
*新添加函数结束
*/